package com.woldier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woldier.common.MyException;
import com.woldier.dto.SetmealDto;
import com.woldier.entity.Setmeal;
import com.woldier.entity.SetmealDish;
import com.woldier.mapper.SetmealMapper;
import com.woldier.service.SetmealDishService;
import com.woldier.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存套餐以及dish
     * @param setmeal
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmeal) {


        /*保存套餐*/
        this.save(setmeal);

        /*保存菜品*/
        List<SetmealDish> dishes = setmeal.getSetmealDishes();

        /*保存之前为所有dish 设置上setmeal的id*/
        Long id = setmeal.getId();
        for (SetmealDish dish : dishes) {
            dish.setSetmealId(id);
        }
        setmealDishService.saveBatch(dishes);


    }

    /*删除套餐以及对应的菜品*/
    @Override
    @Transactional
    public void removeBatchWithDish(List<Long> ids) throws MyException {
        /*查询是否为售卖状态 售卖状态不允许删除*/
        /*构造语句 count(*) from setmeal where id in (1,2,3) and status = 1*/
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(lambdaQueryWrapper);
        /*若威威售卖状态 抛出异常*/
        if(count>0)
            throw new MyException("状态为1不允许删除");
        /*不为售卖状态 删除setmeal表 再删除setmeal_dish*/
        /*删除setmeal表*/
        this.removeByIds(ids);
        /*setmeal_dish*/
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper1 = new LambdaQueryWrapper();
        lambdaQueryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper1);
    }
}
